package com.easyexcle.demo.easyExcel.util;


import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.time.temporal.IsoFields;
import java.time.temporal.TemporalAdjusters;
import java.util.*;

/**
 * @Author: lkz
 * @Title: YearWeekGrouping
 * @Description: 给定一个开始时间 计算时间段内的每一周  只显示周一至周五 年分组 周分组
 * @Date: 2023/5/20 14:02
 */

public class YearWeekGrouping {


    public static void main(String[] args) {
        LocalDate startDate = LocalDate.of(2022, 5, 1);
        LocalDate endDate = LocalDate.of(2023, 5, 31);
        Map<Integer, Map<Integer, List<LocalDate>>> dateMap = groupDatesByYearAndWeek(startDate, endDate);
        for (Map.Entry<Integer, Map<Integer, List<LocalDate>>> yearEntry : dateMap.entrySet()) {
            int year = yearEntry.getKey();
            Map<Integer, List<LocalDate>> weekMap = yearEntry.getValue();
            for (Map.Entry<Integer, List<LocalDate>> weekEntry : weekMap.entrySet()) {
                int weekNum = weekEntry.getKey();
                List<LocalDate> weekDates = weekEntry.getValue();
                System.out.println("Year " + year + ", Week " + weekNum + ": " + weekDates);
            }
        }
    }

    public static Map<Integer, Map<Integer, List<LocalDate>>> groupDatesByYearAndWeek(LocalDate startDate, LocalDate endDate) {
        Map<Integer, Map<Integer, List<LocalDate>>> dateMap = new HashMap<>();
        LocalDate date = startDate.with(TemporalAdjusters.nextOrSame(DayOfWeek.MONDAY));
        while (!date.isAfter(endDate)) {
            int year = date.getYear();
            int weekNum = date.get(IsoFields.WEEK_OF_WEEK_BASED_YEAR);
            Map<Integer, List<LocalDate>> weekMap = dateMap.getOrDefault(year, new HashMap<>());
            List<LocalDate> weekDates = weekMap.getOrDefault(weekNum, new ArrayList<>());
            for (int i = 0; i < 5; i++) {
                if (!date.isAfter(endDate)) {
                    weekDates.add(date);
                    date = date.plusDays(1);
                }
            }
            weekMap.put(weekNum, weekDates);
            dateMap.put(year, weekMap);
        }
        return dateMap;
    }

}
